package com.vxb.testmvp.test_fragment;

import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;

import com.android.volley.RequestQueue;
import com.android.volley.toolbox.Volley;
import com.vxb.testmvp.R;

/**
 * Created by User on 2017/3/2.
 */

public abstract class BaseFragment extends Fragment {

    private LoadingPager loadingPage;


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        if (loadingPage == null) { // 之前的frameLayout 已经记录了一个爹了 爹是之前的ViewPager
            loadingPage = new LoadingPager(getActivity()
                    , R.layout.loadpage_loading
                    , R.layout.loadpage_error
                    , R.layout.loadpage_empty) {
                @Override
                protected LoadResult load() {
                    return BaseFragment.this.load();
                }

                @Override
                protected View createSuccessView() {
                    return BaseFragment.this.createSuccessView();
                }
            };
            loadingPage.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    loadingPage.show();
                }
            });
        } else {
            removeSelfFromParent(loadingPage);// 移除frameLayout之前的爹
        }
        return loadingPage;
    }

    /**
     * 把自身从父View中移除
     */
    public void removeSelfFromParent(View view) {
        // 先找到父类，再通过父类移除孩子
        if (view != null) {
            ViewParent parent = view.getParent();
            if (parent != null && parent instanceof ViewGroup) {
                ViewGroup group = (ViewGroup) parent;
                group.removeView(view);
            }
        }
    }


    public void show() {
        if (loadingPage != null) {
            loadingPage.show();
        }
    }

    /**
     * 刷新页面工程
     *
     * @return
     */
    protected abstract View createSuccessView();

    /**
     * 请求服务器 获取当前状态
     */
    protected abstract LoadingPager.LoadResult load();

}

